﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using GalaSoft.MvvmLight.Messaging;
using JustinAngel.Neurons.Framework.Helpers;
using JustinAngel.Neurons.Framework.Navigation;
using JustinAngel.UnitedNationsNews.AppCore;
using JustinAngel.UnitedNationsNews.Framework;
using JustinAngel.UnitedNationsNews.ItemViewMoels;
using JustinAngel.UnitedNationsNews.Pages.Main;
using JustinAngel.UnitedNationsNews.Services;
using Microsoft.Devices;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Media;
using ResumeMusicPlayTest;
using Microsoft.Unsupported;

namespace JustinAngel.UnitedNationsNews
{
    public partial class MainPage : BasePage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            VM.IsSplashVisible = !App.IsZombification;
            if (VM.IsSplashVisible)
                VisualStateManager.GoToState(this, "IsSplashVisible", true);

            if (!DataService.HasCachedWebRequestResult)
                ShowSplashScreen();

            ZuneMediaHubIntegrationService = IoC.Get<IZuneMediaHubIntegrationService>();
        }

        // this method is in the Page class since we want the splash page to be visible before 
        // databinding or anything else happens. 
        private void ShowSplashScreen()
        {
            FrameworkDispatcher.Update();
            //MediaPlayer.Pause();
            XnaMusicUtil.SaveCurrentMediaState(true);

            //splashMediaElement.MediaOpened += (s, args) => ViewModel.As<MainPageViewModel>().ShowSplashVideo();
            // invoked manually since we can databind to readonly CurrentState property
            splashMediaElement.CurrentStateChanged += (s, args) =>
                {
                    VM.SplashMediaState = splashMediaElement.CurrentState;
                    VM.SplashMediaStateChanged.Execute(null);
                };
        }

        // we're trying to delay the loading of data into the mainpage 
        // until the panorama fully alignes, so we can't put this in a ViewModel. 
        protected override void SetDataContext()
        {
            Dispatcher.BeginInvoke(() =>
            {
                this.DataContext = ViewModel;

                if (this.GetType() == typeof(MainPageViewModel))
                {
                    this.As<MainPageViewModel>().IsLoading = false;
                }
            });
        }

        // remove all page transitions from this page. It's heavy enough without 3d animations. 
        protected override void SetupPageTransitions()
        {
            //base.SetupPageTransitions();
        }

        private void TopStories_Selecitonchanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                e.AddedItems[0].As<ArticleItemViewModel>().NavigateToArticle.Execute(null);

                sender.As<ListBox>().SelectedItem = null;
            }
        }

        private void Section_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                e.AddedItems[0].As<SectionViewModel>().NavigateToSection.Execute(null);

                sender.As<ListBox>().SelectedItem = null;
            }
        }

        private void Videos_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                e.AddedItems[0].As<VideoItemViewModel>().NavigateToVideo.Execute(null);

                sender.As<ListBox>().SelectedItem = null;
            }
        }

        private void Radio_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                e.AddedItems[0].As<RadioItemViewModel>().NavigateToRadio.Execute(null);

                sender.As<ListBox>().SelectedItem = null;
            }
        }

        public MainPageViewModel VM { get { return (MainPageViewModel)this.ViewModel; } }
        private void Photos_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                VM.NavigateToPhotosPage.Execute(null);

                sender.As<ListBox>().SelectedItem = null;
            }
        }

        public IZuneMediaHubIntegrationService ZuneMediaHubIntegrationService { get; set; }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            var result = ZuneMediaHubIntegrationService.LoadHistoryOrNowPlayingTileClick(NavigationContext);
            ViewModel.As<MainPageViewModel>().LoadHistoryOrNowPlayingTileClick(result);

            if (State.ContainsKey("MainPanoramaSelectedItem") && mainPanorama.DefaultItem == null)
            {
                var selIndex = (int)State["MainPanoramaSelectedItem"];
                mainPanorama.DefaultItem = mainPanorama.Items[selIndex];
                State.Remove("MainPanoramaSelectedItem");
            }
        }


        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            State["MainPanoramaSelectedItem"] = mainPanorama.SelectedIndex;
        }
    }


    //public static class ListBoxExtensions
    //{

    //    #region DelayedPanoramaItemSource (Attached DependencyProperty)

    //    public static readonly DependencyProperty DelayedPanoramaItemSourceProperty =
    //        DependencyProperty.RegisterAttached("DelayedPanoramaItemSource", typeof(object), typeof(ListBoxExtensions), new PropertyMetadata(new PropertyChangedCallback(OnDelayedPanoramaItemSourceChanged)));

    //    public static void SetDelayedPanoramaItemSource(ListBox o, object value)
    //    {
    //        o.SetValue(DelayedPanoramaItemSourceProperty, value);
    //    }

    //    public static object GetDelayedPanoramaItemSource(ListBox o)
    //    {
    //        return (object)o.GetValue(DelayedPanoramaItemSourceProperty);
    //    }

    //    private static bool _wasRegistered = false;

    //    private static void OnDelayedPanoramaItemSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    //    {
    //        ListBox sender = (ListBox)d;
    //        var value = e.NewValue;

    //        var parantPanorama = GetParentPanorama(sender);

    //    }

    //    private static Panorama GetParentPanorama(FrameworkElement sender)
    //    {
    //        var parent = VisualTreeHelper.GetParent(sender);
    //        if (parent is Panorama)
    //        {
    //            return (Panorama) parent; 
    //        }
    //        else if (parent == null)
    //        {
    //            throw new Exception("Parent must be a panorama.");
    //        }
    //        else
    //        {
    //            return GetParentPanorama(sender);
    //        }
    //    }

    //    #endregion



    //}

    //public static class PanoramaExtensions
    //{

    //    #region IsVirtualized (Attached DependencyProperty)

    //    public static readonly DependencyProperty IsVirtualizedProperty =
    //        DependencyProperty.RegisterAttached("IsVirtualized", typeof(bool), typeof(PanoramaExtensions), new PropertyMetadata(new PropertyChangedCallback(OnIsVirtualizedChanged)));

    //    public static void SetIsVirtualized(Panorama o, bool value)
    //    {
    //        o.SetValue(IsVirtualizedProperty, value);
    //    }

    //    public static bool GetIsVirtualized(Panorama o)
    //    {
    //        return (bool)o.GetValue(IsVirtualizedProperty);
    //    }

    //    private static void OnIsVirtualizedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    //    {
    //        Panorama sender = (Panorama) d;

    //        sender.SelectionChanged += new EventHandler<SelectionChangedEventArgs>(sender_SelectionChanged);
    //        DispatcherHelper.BeginInvokeOnUIThreadAtEndOfQueue(() =>
    //         DispatcherHelper.BeginInvokeOnUIThreadAtEndOfQueue(() =>
    //         VirtualizedPanorama((Panorama)sender)));
    //    }

    //    private static void VirtualizedPanorama(Panorama sender)
    //    {
    //        List<int> indexOfItemsToNotVirtualized = new List<int>() { sender.SelectedIndex };

    //        if (sender.SelectedIndex - 1 < 0)
    //            indexOfItemsToNotVirtualized.Add(sender.Items.Count - 1);
    //        else
    //            indexOfItemsToNotVirtualized.Add(sender.SelectedIndex - 1);

    //        if (sender.SelectedIndex + 1 == sender.Items.Count)
    //            indexOfItemsToNotVirtualized.Add(0);
    //        else
    //            indexOfItemsToNotVirtualized.Add(sender.SelectedIndex + 1);

    //        for (int i = 0; i < sender.Items.Count; i++)
    //        {
    //            var panoramaItem = (PanoramaItem) sender.Items[0];
    //            if (indexOfItemsToNotVirtualized.Contains(i))
    //            {
    //                if (panoramaItem.Content == null)
    //                {
    //                    panoramaItem.Content = panoramaItem.Tag;
    //                }
    //            }
    //            else if (!indexOfItemsToNotVirtualized.Contains(i))
    //            {
    //                if (panoramaItem.Content != null)
    //                {
    //                    panoramaItem.Tag = panoramaItem.Content;
    //                    panoramaItem.Content = null;
    //                }
    //            }
    //        }
    //    }

    //    static void sender_SelectionChanged(object sender, SelectionChangedEventArgs e)
    //    {
    //        if (e.AddedItems.Count > 0)
    //        {
    //            DispatcherHelper.BeginInvokeOnUIThreadAtEndOfQueue(() => 
    //                DispatcherHelper.BeginInvokeOnUIThreadAtEndOfQueue(() =>
    //                VirtualizedPanorama((Panorama) sender)));
    //        }
    //    }

    //    #endregion

    //}


}